
package com.hnrd.crud.utils;

import java.time.ZoneId;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

public class JWTTokenUtil {

	private final static String SECRET = "hnrd";
	private static final Logger log = LoggerFactory.getLogger(JWTTokenUtil.class);
 
	/**
	 * 生成token的方法
	 */
	public static String createToken(String username) {
		// 签发时间
		Date itaDate = new Date();
		// 设定过期时间
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MINUTE, 600);
		Date expireDate = calendar.getTime();
		// 设置header信息，map
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("alg", "HS256");
		map.put("typ", "JWT");

		// 创建Token
		String Token = JWT.create().withHeader(map).withClaim("username", username).withExpiresAt(expireDate)// 设置过期时间
				.withIssuedAt(itaDate)// 设置签发时间
				.sign(Algorithm.HMAC256(SECRET));
		return Token;
	}
	/**
	 * 生成token的方法
	 */
	public static String createToken(String username,String password) {
		// 签发时间
		Date itaDate = new Date();
		// 设定过期时间
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MINUTE, 600);
		Date expireDate = calendar.getTime();
		// 设置header信息，map
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("alg", "HS256");
		map.put("typ", "JWT");

		// 创建Token
		String Token = JWT.create().withHeader(map).withClaim("username", username).withClaim("password", password).withExpiresAt(expireDate)// 设置过期时间
				.withIssuedAt(itaDate)// 设置签发时间
				.sign(Algorithm.HMAC256(SECRET));
		return Token;
	}

	/**
	 * 验证过期时间
	 */
	public static boolean validateToken(String token) {
		DecodedJWT jwt = JWT.decode(token);
		log.info("token过期时间：" + jwt.getExpiresAt().toInstant().atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime());
		Date newDate = new Date();
		log.info("当前时间"+newDate);
		if (newDate.compareTo(jwt.getExpiresAt()) == 1) {
			return false;
		}
		return true;
	}

	/**
	 * 获得token中的信息无需secret解密也能获得
	 * @return token中包含的用户名
	 */
	public static String getUsername(String token) {
		try {
			DecodedJWT jwt = JWT.decode(token);
			return jwt.getClaim("username").asString();
		} catch (JWTDecodeException e) {
			return null;
		}
	}
	/**
	 * 获取token中获取的密码信息
	 * @param token
	 * @return
	 */
	public static String getPassword(String token) {
		try {
			DecodedJWT jwt =JWT.decode(token);
			return jwt.getClaim("password").asString();
		} catch (Exception e) {
			return null;
		}
		
	}
}
